<?php
session_start(); if (!isset($_SESSION['uid'])) header('Location: login.php');
require_once 'config.php';
function db(): PDO {
    static $pdo; if (!$pdo) {
        $dsn = "mysql:host=$GLOBALS[DB_HOST];dbname=$GLOBALS[DB_NAME];charset=$GLOBALS[DB_CHAR]";
        $pdo = new PDO($dsn, $GLOBALS['DB_USER'], $GLOBALS['DB_PASS'], [PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
    } return $pdo;
}
$type = $_GET['type'] === 'OUT' ? 'OUT' : 'IN';
if ($_POST && isset($_POST['items'])) {
    $pdo = db(); $pdo->beginTransaction();
    $ord = $pdo->prepare('INSERT INTO orders(type,number) VALUES(?,?)');
    $ord->execute([$type, date('YmdHis')]); $ordId = $pdo->lastInsertId();

    $item = $pdo->prepare('INSERT INTO order_item(order_id,goods_id,qty) VALUES(?,?,?)');
    $stockSel = $pdo->prepare('SELECT qty FROM stock WHERE goods_id=?');
    $stockIns = $pdo->prepare('INSERT INTO stock(goods_id,qty) VALUES(?,?)');
    $stockUpd = $pdo->prepare('UPDATE stock SET qty=? WHERE goods_id=?');

    foreach ($_POST['items'] as $i) {
        $gid = (int)$i['goods_id']; $qty = (int)$i['qty'];
        if ($qty <= 0) continue;
        $item->execute([$ordId, $gid, $qty]);
        $stockSel->execute([$gid]); $row = $stockSel->fetch();
        if ($row) {
            $new = $type==='IN' ? $row['qty'] + $qty : $row['qty'] - $qty;
            $stockUpd->execute([$new, $gid]);
        } else {
            if ($type==='IN') $stockIns->execute([$gid, $qty]);
        }
    }
    $pdo->commit();
    header('Location: stock.php'); exit;
}
$goods = db()->query('SELECT id,name,code,unit FROM goods ORDER BY name')->fetchAll();
?>
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <title><?= $type==='IN' ? '入库单' : '出库单' ?> - 仓库管理系统 V 1.0</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <link rel="stylesheet" href="bootstrap.min.css">
</head>
<body>
<nav class="navbar navbar-dark bg-primary">
  <div class="container-fluid">
    <span class="navbar-brand fw-bold">仓库管理系统 V 1.0</span>
    <a class="btn btn-outline-light btn-sm" href="index.php">返回首页</a>
  </div>
</nav>
<div class="container py-4">
  <h5><?= $type==='IN' ? '新建入库单' : '新建出库单' ?></h5>
  <form method="post" id="orderForm">
    <div class="table-responsive">
      <table class="table table-bordered" id="itemTable">
        <thead class="table-light">
          <tr><th>商品</th><th>数量</th><th class="text-center">操作</th></tr>
        </thead>
        <tbody>
        <tr>
          <td>
            <select name="items[0][goods_id]" class="form-select" required>
              <option value="">请选择商品</option>
              <?php foreach ($goods as $g): ?>
                <option value="<?= $g['id'] ?>"><?= $g['name'] ?> (<?= $g['code'] ?>)</option>
              <?php endforeach; ?>
            </select>
          </td>
          <td><input type="number" name="items[0][qty]" min="1" class="form-control" required></td>
          <td class="text-center"><button type="button" class="btn btn-outline-danger btn-sm" onclick="delRow(this)">删除</button></td>
        </tr>
        </tbody>
      </table>
    </div>
    <button type="button" class="btn btn-outline-primary btn-sm mb-2" onclick="addRow()">+ 添加一行</button>
    <button type="submit" class="btn btn-success">保存单据</button>
  </form>
</div>
<script>
let idx = 1, opts = `<?php foreach ($goods as $g) echo "<option value='{$g['id']}'>{$g['name']} ({$g['code']})</option>"; ?>`;
function addRow() {
  const tr = `<tr>
    <td><select name="items[\${idx}][goods_id]" class="form-select" required>${opts}</select></td>
    <td><input type="number" name="items[\${idx}][qty]" min="1" class="form-control" required></td>
    <td class="text-center"><button type="button" class="btn btn-outline-danger btn-sm" onclick="delRow(this)">删除</button></td>
  </tr>`;
  document.getElementById('itemTable').insertAdjacentHTML('beforeend', tr); idx++;
}
function delRow(btn) { btn.closest('tr').remove(); }
</script>
<script src="bootstrap.bundle.min.js"></script>
</body>
</html>